package com.dhms.vostok1.repository

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.dhms.vostok1.data.todo.ToDoCenterData
import com.dhms.vostok1.data.todo.ToDoCenterListQueryData
import com.dhms.vostok1.service.net.NetworkApi
import com.dhms.vostok1.utils.toMap

class ToDoCenterListPagingSource(
    val api: NetworkApi,
    private val toDoCenterConditions: ToDoCenterListQueryData,
    private val isLoadMore: Boolean = true
) : PagingSource<Int, ToDoCenterData>() {
    override fun getRefreshKey(state: PagingState<Int, ToDoCenterData>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ToDoCenterData> {
        val pos = params.key ?: 1
        var nextPageNumber: Int? = pos + 1
        val message = "获取待办中心任务列表数据失败"

        try {
            val conditions = toDoCenterConditions
            conditions.page = pos
            val queryMap = conditions.toMap()!!
            val res = api.getToDoCenterList(queryMap)
            val error = res.exceptionOrNull()
            if (error != null) {
                // 数据获取失败
                Log.e(TAG, "error: $error")
                return LoadResult.Error(Throwable(message, error))
            }
            val items = res.getOrNull()?.body()?.data?.items ?: listOf()
            if (items.size < toDoCenterConditions.perPage || !isLoadMore) {
                nextPageNumber = null
            }
            return LoadResult.Page(
                data = items,
                if (pos <= 1) null else pos - 1,
                nextPageNumber
            )
        } catch (error: Throwable) {
            return LoadResult.Error(Throwable(message, error))
        }
    }

    companion object {
        const val TAG = "ToDoCenterListPagingSource"
    }
}
